package com.yupi.springbootinit.job.once;

/*
* 获取初始帖子列表
* */

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
* 定时任务
* 当Component注解生效时，springboot项目在启动时会调用该定时任务中的方法一次
* */

//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Override
    public void run(String... args) throws Exception {
        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"_score\",\"sortOrder\":\"descend\",\"searchText\":\"java面试\",\"category\":\"文章\",\"reviewStatus\":1}";
        String url = "https://www.code-nav.cn/api/post/search/page/vo";
        // 获得指定url接口返回的数据(JSON格式)
        String body = HttpRequest.post(url)
                .body(json)
                .execute()
                .body();
//        System.out.println(body);
        // 将 JSON 格式的数据转换为map
        Map<String,Object> map = JSONUtil.toBean(body, Map.class);
        List<Post> postList =new ArrayList<>();
        if (!map.isEmpty()) {
            JSONObject data = (JSONObject) map.get("data");
            JSONArray records =(JSONArray)data.get("records");
            for (Object record : records) {
                // record是一个JSONObject类的对象，将其强转的目的是为了调用 JSONObject的方法
                JSONObject tempRecord =(JSONObject)record;
                Post post=new Post();
                post.setTitle((String)tempRecord.get("title"));
                post.setContent((String)tempRecord.get("content"));
                JSONArray tags =(JSONArray)tempRecord.get("tags");
                List<String> tagList = tags.toList(String.class);
                post.setTags(JSONUtil.toJsonStr(tagList));
                post.setUserId(1681187572483321857L);
                postList.add(post);
            }
            boolean b = postService.saveBatch(postList);
            if(b){
                log.info("postList初始化成功，条数={}",postList.size());
            }else{
                log.error("postList初始化失败");
            }
        }
    }
}
